package com.my.home.common.intercepter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import utils.DateUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;

/**
 * 日志拦截
 * Created by Al Sah-him on 2018/7/3.
 */
public class LogIntercepter implements HandlerInterceptor{

    protected Logger logger= LoggerFactory.getLogger(LogIntercepter.class);
    private static final ThreadLocal<Long> threadLocal=new NamedThreadLocal<>("ThreadLocal start!");
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        Long startTime=System.currentTimeMillis();
        threadLocal.set(startTime);
        logger.debug("开始计时:{}, URI:{}",new SimpleDateFormat("hh:mm:ss.SSS")
                .format(startTime),httpServletRequest.getRequestURI());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        if(modelAndView!=null){
            logger.debug("viewName:{}",modelAndView.getViewName());
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        Long startTime=threadLocal.get();
        Long now=System.currentTimeMillis();
        logger.debug("计时结束:{} 耗时:{} URI:{}  最大内存: {}m  已分配内存: {}m  已分配内存中的剩余空间: {}m  最大可用内存: {}m",new SimpleDateFormat("hh:mm:ss.SSS")
        .format(now), DateUtils.formatDateTime(now-startTime),httpServletRequest.getRequestURI(),Runtime.getRuntime().maxMemory()/1024/1024,
        Runtime.getRuntime().totalMemory()/1024/1024,Runtime.getRuntime().freeMemory()/1024/1024,
                (Runtime.getRuntime().maxMemory()-Runtime.getRuntime().totalMemory()+Runtime.getRuntime().freeMemory())/1024/1024);
    }
}
